package com.example.gulimall.product.service.impl;

import com.example.common.constant.CommonConstant;
import com.example.gulimall.product.entity.SkuImagesEntity;
import com.example.gulimall.product.entity.SpuInfoDescEntity;
import com.example.gulimall.product.service.*;
import com.example.gulimall.product.vo.SkuItemSaleAttrVo;
import com.example.gulimall.product.vo.SkuItemVo;
import com.example.gulimall.product.vo.SpuItemAttrGroupVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.SkuInfoDao;
import com.example.gulimall.product.entity.SkuInfoEntity;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<SkuInfoEntity>();
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(item->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotBlank(catelogId) && !CommonConstant.NUMBER_0.equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId) && !CommonConstant.NUMBER_0.equals(catelogId)){
            wrapper.eq("brand_id",brandId);
        }
        //大于
        String min = (String) params.get("min");
        if(StringUtils.isNotBlank(min) ){
            wrapper.ge("price",min);
        }
        //小于
        String max = (String) params.get("max");
        if(StringUtils.isNotBlank(max) && new BigDecimal(max).compareTo(BigDecimal.ZERO)==1){
            wrapper.le("price",max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> entityList = this.baseMapper.
                selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return entityList;
    }

    /**
     * 根据SKUID查询商品信息AND异步编排
     * @author GuLin
     * @date 14:51 2021/6/28
     * @param skuId
     * @return com.example.gulimall.product.vo.SkuItemVo
     **/
    @Override
    public SkuItemVo queryItemBySkuId(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();

        //1、sku基本信息的获取  pms_sku_info
        CompletableFuture<SkuInfoEntity> skuFuture = CompletableFuture.supplyAsync(()->{
            SkuInfoEntity infoEntity = this.getById(skuId);
            skuItemVo.setInfo(infoEntity);
            return infoEntity;
        },executor);
        //3、获取spu的销售属性组合
        CompletableFuture<Void> attrFuture = skuFuture.thenAcceptAsync((res) -> {
            List<SkuItemSaleAttrVo> saleAttr = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttr);
        });
        //4、获取spu的介绍
        CompletableFuture<Void> desFuture = skuFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity desc = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(desc);
        });
        //5、获取spu的规格参数信息
        CompletableFuture<Void> groupAttrsFuture = skuFuture.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        });

        //2、sku的图片信息    pms_sku_images
        CompletableFuture<Void> imagesRunAsync = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = skuImagesService.selectSkuImagesList(skuId);
            skuItemVo.setImages(images);
        });
        //等待所有任务完成
        try {
            CompletableFuture.allOf(attrFuture,desFuture,groupAttrsFuture,imagesRunAsync).get();
        } catch (Exception e) {
            log.error("商品详情查询异常:{}",e.getMessage());
        }
        //log.info(skuItemVo.toString());
        return skuItemVo;
    }

}